package com.codeiy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.codeiy.criteria.CriteriaQuery;
import com.codeiy.dto.R;
import com.codeiy.entity.meta.MetaField;
import com.codeiy.entity.meta.MetaObject;
import com.codeiy.service.MetaFieldService;
import com.codeiy.service.MetaObjectService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/object")
public class MetaObjectController {
    private final MetaObjectService metaObjectService;
    private final MetaFieldService metaFieldService;

    /**
     * 通过ID查询
     *
     * @param id ID
     * @return MetaObject
     */
    @GetMapping("/{id:\\d+}")
    public R<MetaObject> getById(@PathVariable Long id) {
        return R.ok(metaObjectService.getById(id));
    }

    /**
     * 查询分页信息
     *
     * @param criteriaQuery 查询对象
     * @return 分页对象
     */
    @PostMapping("/page")
    public R<IPage<MetaObject>> page(@RequestBody CriteriaQuery criteriaQuery) {
        return R.ok(metaObjectService.page(criteriaQuery.toMybatisPlusPage(), criteriaQuery.toQueryWrapper()));
    }

    /**
     * 添加
     *
     * @param metaObject 实体
     * @return success/false
     */
    @PostMapping
    public R<Boolean> save(@RequestBody MetaObject metaObject) {
        return R.ok(metaObjectService.save(metaObject));
    }

    /**
     * 删除
     *
     * @param id ID
     * @return success/false
     */
    @DeleteMapping("/{id:\\d+}")
    public R<Boolean> removeById(@PathVariable Long id) {
        return R.ok(metaObjectService.removeById(id));
    }

    /**
     * 编辑
     *
     * @param metaObject 实体
     * @return success/false
     */
    @PutMapping
    public R<Boolean> update(@RequestBody MetaObject metaObject) {
        return R.ok(metaObjectService.updateById(metaObject));
    }

    /**
     * 根据对象编码查询表信息
     *
     * @param objectCode 对象编码
     * @return
     */
    @GetMapping("/details/{projectCode}/{objectCode}")
    public R<MetaObject> detail(@PathVariable String projectCode, @PathVariable String objectCode) {
        MetaObject condition = new MetaObject();
        condition.setProjectCode(projectCode);
        condition.setObjectCode(objectCode);
        MetaObject metaObject = metaObjectService.getOne(new QueryWrapper<>(condition));
        setFields(metaObject);
        return R.ok(metaObject);
    }

    private void setFields(MetaObject metaObject) {
        MetaField condition = new MetaField();
        condition.setProjectCode(metaObject.getProjectCode());
        condition.setObjectCode(metaObject.getObjectCode());
        List<MetaField> fields = metaFieldService.list(new QueryWrapper<>(condition));
        metaObject.setFields(fields);
    }
}
